package org.example.shortlink.admin.controller;

import lombok.RequiredArgsConstructor;
import org.example.shortlink.admin.common.convention.Result;
import org.example.shortlink.admin.common.convention.Results;
import org.example.shortlink.admin.common.enums.errorcode.UserErrorCode;
import org.example.shortlink.admin.common.exception.ClientException;
import org.example.shortlink.admin.dto.req.UserLoginReqDTO;
import org.example.shortlink.admin.dto.req.UserRegisterReqDTO;
import org.example.shortlink.admin.dto.req.UserUpdateReqDTO;
import org.example.shortlink.admin.dto.resp.UserLoginRespDTO;
import org.example.shortlink.admin.dto.resp.UserRespDTO;
import org.example.shortlink.admin.service.UserService;
import org.springframework.web.bind.annotation.*;

/**
 * @author czj
 */
@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/api/short-link/v1/user/{username}")
    public Result<UserRespDTO> getUser(@PathVariable("username") String username) {
        UserRespDTO user = userService.getUserByUserName(username);
        if (user != null) {
            return new Result<UserRespDTO>().setCode("0").setData(user);
        } else {
            throw  new ClientException(UserErrorCode.USER_NULL);
        }
    }

    @GetMapping("/api/short-link/v1/user/available-user")
    public Result<Boolean> availableUser(@RequestParam("username") String username) {
        return Results.success(userService.availableUsername(username));
    }

    @PostMapping("/api/short-link/v1/user")
    public Result<Void> register(@RequestBody UserRegisterReqDTO registerDTO) {
        userService.register(registerDTO);
        return Results.success();
    }

    @PutMapping("/api/short-link/v1/user")
    public Result<Void> updateUser(@RequestBody UserUpdateReqDTO updateDTO) {
        userService.updateUser(updateDTO);
        return Results.success();
    }

    @PostMapping("/api/short-link/v1/user/login")
    public Result<UserLoginRespDTO> login(@RequestBody UserLoginReqDTO loginDTO) {
        return Results.success(userService.login(loginDTO));
    }

    @GetMapping("/api/short-link/v1/user/check-login")
    public Result<Boolean> checkLogin(String username, String token) {
        return Results.success(userService.checkLogin(username,token));
    }

    @PostMapping("/api/short-link/v1/user/logout")
    public Result<Void> logout(String username, String token) {
        userService.logout(username,token);
        return Results.success();
    }
}
